import {useUserStore} from '@/stores/modules/user.store'
import {isEmpty} from 'lodash-es'
import {DEFAULT_USER} from '@/utils/constantsUtil'
import {Local} from '@/utils/storageUtil'
import {cacheKeys} from '@/stores/constant/cacheKey'

/**
 * 权限检查方法，入参的资源编码为多个时，至少一个具有权限即可
 * @param value 单个或多个资源编码
 * @return boolean 是否有权限
 */
export const hasPermission: (value: Arrayable<string>) => boolean = (value) => {
	if (isEmpty(value)) {
		return true
	}
	// 获取用户页面组件权限 - 从后台拿数据
	const dynamicButtons = useUserStore().buttons
	if (isEmpty(dynamicButtons)) {
		return false
	}
	if (Array.isArray(value)) {
		return dynamicButtons.some(button => value.includes(button.resources))
	} else {
		return dynamicButtons.some(button => button.resources === value)
	}
}

/**
 * 判断当前登录用户是否为管理员
 */
export const isAdmin: () => boolean = () => {
	return useUserStore().isAdmin === true
}

/**
 * 判断当前登录用户是否为内置游客
 */
export const isVisitor: () => boolean = () => {
	return useUserStore().username === DEFAULT_USER.VISITOR_USERNAME
}

/**
 * 检查登录状态
 * @return string|undefined 未登录返回提示信息，已登录返回undefined
 */
export const checkLogin = async (): Promise<string | undefined> => {
	const token = Local.get(cacheKeys.TOKEN)
	if (!token) {
		return '未登录'
	}
	// 检查token是否过期
	const expire = Local.get(cacheKeys.EXPIRE)
	if (!expire || new Date(expire).getTime() < new Date().getTime()) {
		await useUserStore().logout()
		Local.remove(cacheKeys.TOKEN)
		return '登录超时'
	}
	return undefined
}
